<?php

namespace App\Http\Controllers\Innerend;


use App\Models\ArticleComment;
use App\Models\FangtanUser;
use App\Models\Fresh;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class FangtanUserController extends BaseController
{
    protected $list_cache = true;

    // 快讯
    public function initialize()
    {
        parent::initialize();

        $fangtan_id = $this->getData('fangtan_id', 0, 'intval');
        $is_online = $this->getData('is_online', 0, 'intval');
        $url = url('/innerend/fangtan-user/lists?fangtan_id='.$fangtan_id.'&is_online='.$is_online);

        $this->assign('init_url', $url);
        $this->model = 'FangtanUser';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作

    // 返回列表数据（待删除）
    public function _lists()
    {
        $keyword = $this->getData('keyword', null, 'trim');
        $itype   = $this->getData('itype', '', 'trim');
        $ft_id   = $this->getData('fangtan_id', 0, 'intval');
        $this->throwIf(empty($ft_id), '请指定访谈编号！');

        $page  = $this->page;
        $rows  = $this->rows;
        $where = [['fangtan_id', '=', $ft_id]];
        if($itype){
            $where[] = ['itype', '=', $itype];
        }

        // 查询
        $model  = new FangtanUser();
        $result = $model->bangField(['fangtan_id'])->listPage($where, $page, $rows, "id DESC");

        // 用户头像，粉丝数量，关注数量，金币数
        if($result['list']){
            $userDb = new User();
            $uids   = array_column($result['list'], 'uid');
            $users  = $userDb->isCache(true)->getListInIds($uids);
            $users  = array_column($users, null, 'id');
            $types  = $this->userType(); // 认证类型
            foreach($result['list'] as $key => $item){
                $_uid  = $item['uid'];
                $_user = $users[$_uid] ?? [];

                // 整理
                if($_user){
                    // $_user['apply_type'] = $types[$_user['apply_type']]['name'] ?? '';
                    $_user['apply_type'] = $_user['is_apply'] == 1 ? ($types[$_user['apply_type']]['name'] ?? '') : '';
                    $_user['head_img']   = $this->getHeadImg($_user['head_img'] ?? '');
                } else{
                    $_user = (object)[];
                }

                // 整理
                $result['list'][$key]['user'] = $_user;
            }
        }

        return $this->success($result);
    }

    // 列表数据展示
    protected function listTable($lists)
    {
        // 整理
        $fangtan_id = $this->getData('fangtan_id', 0, 'intval');
        $trList     = [];
        if(empty($lists)){
            return ['list' => $lists, 'tr' => $trList];
        }

        $userDb = new User();
        $uids   = array_column($lists, 'uid');
        $users  = $userDb->isCache(true)->getListInIds($uids);
        $types  = $this->userType(); // 认证类型
        $all    = ['guest' => '嘉宾', 'host' => '主持', 'no_jion' => '禁止参加', 'no_speaking' => '禁止发言'];

        // 展示列表表格
        $listHtml = $this->adminList();
        foreach($lists as $key => $item){
            // 数据
            $_id   = $item['id'];
            $_uid  = $item['uid'];
            $_user = $users[$_uid] ?? [];
            // 操作
            $operate = '';
            $param   = ['fangtan_id' => $fangtan_id, 'id' => $_id];
            /*$operate .= $listHtml->operate_list($param, '用户报名', '/fangtan-appoint/lists');
            $operate .= $listHtml->operate_list($param, '访谈问答', '/fangtan-fresh/answer');
            $operate .= $listHtml->operate_list($param, '访谈内容', '/fangtan-fresh/interview');*/
            $operate .= $listHtml->operate_edit($param, '编辑');
            $operate .= $listHtml->operate_delete($param, '你确定要删除该用户吗？');
            //$operate .= $listHtml->operate_soft_delete($param, '你确定要删除该用户吗？');

            // 头像
            $head_img  = $this->getHeadImg($_user['head_img'] ?? '');
            $imageHtml = "<img src='".$head_img."' style='width:100px;' >";


            // 页面
            $tr = $listHtml->list_check($_id);
            $tr .= $listHtml->list_td($_uid);
            $tr .= $listHtml->list_td($_user['username'] ?? '');
            $tr .= $listHtml->list_td($all[$item['itype']] ?? '-');
            //$tr .= $listHtml->list_td($imageHtml);
            $tr .= $listHtml->list_td(date('Y-m-d H:i', $item['ctime']));
            $tr .= $listHtml->list_td($operate);
            $tr .= $operate;

            // 整合
            $trList[] = $listHtml->list_tr($tr);
        }

        // 整合
        return ['list' => $lists, 'tr' => $trList];
    }

    // 列表字段
    protected function list_fields()
    {
        return ['uid' => '账户名', 'username' => '账户名', 'itype' => '状态', 'ctime' => '创建时间', 'operate' => ['操作', 250],];
    }

    // 列表搜索
    protected function list_search()
    {
        $request = $this->getData();
        $form    = $this->adminList();
        $keyword = $form->formInput('keyword', $request['keyword'] ?? '', '关键字');
        $datemin = $form->formDateTime('datemin', $request['datemin'] ?? '', '开始时间', 'datetime');
        $datemax = $form->formDateTime('datemax', $request['datemax'] ?? '', '结束时间', 'datetime');

        $search = ['keyword' => $keyword, 'datemin' => $datemin, 'datemax' => $datemax,];  // 'is_top' => $is_top,
        $this->assign('search', []);

        $searchHide = ['is_online', 'fangtan_id'];
        $this->assign('searchHide', $searchHide);
    }

    // 列表查询
    protected function listWhere()
    {
        $keyword    = $this->getData('keyword', null, 'trim');
        $fangtan_id = $this->getData('fangtan_id', 0, 'intval');
        $isLine     = $this->getData('is_online', 1, 'intval');
        $where      = [['fangtan_id', '=', $fangtan_id], ['itype', '!=', 'appoint'],]; // ['verify', '=', 1],
        /*if($keyword){
            $where[] = $this->orWhere('title|description', 'like', $keyword);
            // 不在缓存
            $this->list_cache = false;
        }*/

        return $where;
    }

    // 列表顶部按钮
    protected function listTopButton()
    {
        $fangtan_id = $this->getData('fangtan_id', 0, 'intval');
        $addUrl     = url('/innerend/'.$this->controller.'/add?fangtan_id='.$fangtan_id);
        $top_button = '<a href="javascript:;" onclick="onEdit(\''.$addUrl.'\')" class="btn btn-success radius">添加</a> ';
        $this->assign('top_button', $top_button);
    }

    // 表单页面
    protected function formTable()
    {
        $html = '';
        $info = $this->onShow();
        $form = $this->adminForm();
        $all  = ['guest' => '嘉宾', 'host' => '主持', 'no_jion' => '禁止参加', 'no_speaking' => '禁止发言'];

        $fangtan_id = $this->getData('fangtan_id', 0, 'intval');
        $username   = $form->ajaxSearch('uid', $info['uid'] ?? '', 'User');
        $itype      = $form->formSelect('itype', $info['itype'] ?? '', $all);
        $fangtan_id = $form->formHidden('fangtan_id', $info['fangtan_id'] ?? $fangtan_id);
        $_id        = $form->formHidden('id', $info['id'] ?? '');

        $html .= $fangtan_id;
        $html .= $_id;
        $html .= $form->makeItem('用户', $username);
        $html .= $form->makeItem('用户类型', $itype);

        return $html;
    }


    // 删除（软删除）
    public function del()
    {
        $ft_id = $this->getData('fangtan_id', 0, 'intval');
        $this->throwIf(empty($ft_id), '请指定访谈编号！');
        $this->throwIf(empty($this->id), '请指定删除记录！');

        $where  = ['id' => $this->id, 'fangtan_id' => $ft_id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->oneDelete($where);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 查找
    public function show()
    {
        $ft_id = $this->getData('fangtan_id', 0, 'intval');
        $this->throwIf(empty($ft_id), '请指定访谈编号！');
        $this->throwIf(empty($this->id), '请指定查看记录');

        $where = [['id', '=', $this->id], ['fangtan_id', '=', $ft_id]];
        $model = $this->checkModel($this->model);
        $info  = $model->isCache(true)->oneFind($where);
        $this->throwIf($info === false, $model->getError());
        $this->throwIf(empty($info), '你要查看的访谈用户不存在！');

        // 查找用户信息
        if($info['uid']){
            $uid    = $info['uid'];
            $userDb = new User();
            $types  = $this->userType(); // 认证类型
            // $user   = $userDb->isCache(true)->getListInIds([$uid]);
            $user = $userDb->isCache(true)->getOneById($uid);
            if($user){
                // $user               = $user[$uid];
                $user['head_img']   = $this->getHeadImg($user['head_img'] ?? '');
                $user['apply_type'] = $user['is_apply'] == 1 ? ($types[$user['apply_type']]['name'] ?? '') : '';
                // $user['apply_type'] = $types[$user['apply_type']]['name'] ?? '';
            }
            $info['user'] = $user;
        }

        return $this->success($info);
    }

    // 启用禁用
    public function status()
    {
        $_value = $this->getData('status', 0, 'intval');
        $this->throwIf(is_null($_value), '是否启用状态必须填写！');
        $this->throwIf(!in_array($_value, [0, 1]), '是否启用状态必须为0或1！');

        return $this->changeField('status', $_value);
    }

    // 添加（添加多个）
    public function _add()
    {
        $typeArr = ['guest', 'host', 'no_jion', 'no_speaking', 'to_jion',];
        $itype   = $this->getData('itype', '', 'trim');
        $ft_id   = $this->getData('fangtan_id', 0, 'intval');
        $uids    = $this->getData('uids', [], 'is_array');
        $this->throwIf(empty($ft_id), '请指定访谈编号！');
        $this->throwIf(empty($itype), '请指定访谈用户类型！');
        $this->throwIf(!in_array($itype, $typeArr), '请指定正确访谈用户类型！');
        $this->throwIf(count($uids) != count($uids, 1), '请指定访谈用户编号！');

        // 查看数据是否存在
        $ftUserDb = new FangtanUser();
        $lists    = $ftUserDb->where('fangtan_id', $ft_id)->whereIn('uid', $uids)->get()->toArray();
        // 用户数据整理
        $addUid = $uids;
        $delUid = $changeUid = [];
        if($lists){
            foreach($lists as $item){
                $status   = $item['status'];
                $_uid     = $item['uid'];
                $delUid[] = $_uid;
                if($status == 0){
                    $changeUid[] = $_uid;
                }
            }
        }
        if($delUid){
            $addUid = array_diff($addUid, $delUid);
        }

        // 如果不存在，则添加
        $addData = [];
        if($addUid){
            foreach($addUid as $_uid){
                $addData[] = ['status' => 1, 'fangtan_id' => $ft_id, 'uid' => $_uid, 'itype' => $itype, 'ctime' => LARAVEL_TIME, 'mtime' => LARAVEL_TIME,];
            }
        }
        DB::beginTransaction();
        try{
            // 如果存在，则改变状态
            if($changeUid){
                $ftUserDb->where('fangtan_id', $ft_id)->whereIn('uid', $changeUid)->update(['status' => 1]);
            }
            // 如果不存在，则添加
            if($addData){
                $ftUserDb->insert($addData);
            }
            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 删除缓存
        $cacheData = ['status' => 1, 'fangtan_id' => $ft_id, 'itype' => $itype];
        $ftUserDb->bangField(['fangtan_id'])->deleteCacheShow($cacheData);

        return $this->success();
    }

    // 添加
    protected function _before_add()
    {
        $data = [
            // 'id'         => $this->getData("id"),
            'fangtan_id' => $this->getData("fangtan_id"),
            'uid'        => $this->getData("uid"),
            'itype'      => $this->getData("itype"),
            'status'     => $this->getData("status", 1, 'intval'),
            // 'ctime'      => $this->getData("ctime"),
            // 'mtime'      => $this->getData("mtime"),
        ];

        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        $data = [
            'fangtan_id' => $this->getData("fangtan_id"),
            'uid'        => $this->getData("uid"),
            'itype'      => $this->getData("itype"),
            'status'     => $this->getData("status", 1, 'intval'),
        ];

        return $data;
    }

}


